package com.java.netty.codec2;

import com.java.netty.codec.StudentPOJO;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.util.CharsetUtil;

import java.util.Random;

/**
 * @author jl
 * Created on 2020/9/29
 */
public class NettyClientHandler extends ChannelInboundHandlerAdapter {

    // 当通道就绪就会触发该方法,向服务器发送消息
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        // 随机发送一个boss/worker对象到服务器
        MyMessagePOJO.MyMessage myMessage = null;
        if (new Random().nextInt(10) / 2 == 0) {
            myMessage = MyMessagePOJO.MyMessage.newBuilder().setDataType(MyMessagePOJO.MyMessage.DataType.BossType)
                    .setBoss(MyMessagePOJO.Boss.newBuilder().setId(100).setName("老板").build()).build();
        } else {
            myMessage = MyMessagePOJO.MyMessage.newBuilder().setDataType(MyMessagePOJO.MyMessage.DataType.WorkerType)
                    .setWorker(MyMessagePOJO.Worker.newBuilder().setAge(25).setAddress("武汉").build()).build();
        }
        ctx.writeAndFlush(myMessage);
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        ByteBuf byteBuf = (ByteBuf) msg;
        System.out.println("收到服务器的消息是:" + byteBuf.toString(CharsetUtil.UTF_8));
        System.out.println("服务器的地址是:" + ctx.channel().remoteAddress());
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        cause.printStackTrace();
        ctx.close();
    }
}
